﻿using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;

namespace Billder
{
    public class OTable
    {
        public string sourceCmd;
        public Table theTable;
        public TableRow header;
        public List<OColumn> columns;
        public OTable(string sourceCmd)
        {
            this.sourceCmd = sourceCmd;
            theTable = new Table();
            header = new TableRow();
            columns = new List<OColumn>();

        }

        public OTable(string sourceCmd, List<OColumn> columns)
            : this(sourceCmd)
        {
            this.columns = columns;
        }
        public Table getTable(string sort , string filter, string pk) {
            DataSet ds = new System.Data.DataSet();
            SqlDataAdapter da = new SqlDataAdapter(sourceCmd,
                System.Configuration.ConfigurationManager.ConnectionStrings["Billder"].ConnectionString);
            da.Fill(ds);
            DataTable dt = ds.Tables[0];
            if (columns.Count == 0) {
                foreach (DataColumn col in dt.Columns)
                {
                    columns.Add( new OColumn( col.ColumnName ) );
                }
            }
            foreach (OColumn col in columns)
            {
                TableCell cell = new TableCell();
                cell.Text=col.label;
                header.Cells.Add(cell);
            }
            header.TableSection = TableRowSection.TableHeader;
            theTable.Rows.Add(header);
            bool odd = true;
            DataView dv = dt.AsDataView();
            dv.Sort= sort ;
            dv.RowFilter = filter;
            foreach (DataRow row in dv.ToTable().Rows)
            {
                TableRow tRow = new TableRow();
                foreach (OColumn col in columns)
                {
                    TableCell tCell = new TableCell();
                    tCell.Text = row[col.columnName].ToString();
                    tRow.Cells.Add(tCell);
                }
                tRow.TableSection = TableRowSection.TableBody;
                tRow.Attributes.Add( "ondblclick"  , "prepareEdit('"+row[pk].ToString()+"');");
                if (odd)
                {
                    tRow.CssClass = "odd";
                }
                theTable.Rows.Add(tRow);
                odd = !odd;
            }
            return theTable;
        }
    }
}